<template>
  <div>
    <a-spin :spinning="loading">
      <a-icon slot="indicator" type="loading" spin />
      <a-button v-if="displayType === 'BUTTON'" type="primary" @click="showConfirm">{{ text }} {{ downloadPercent }}</a-button>
      <a v-if="displayType === 'LINK'"  @click="handleDownload">{{ text }} {{ downloadPercent }}</a>
    </a-spin>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  props: {
    text: { type: [String] },
    rows: { type: [Array], default: () => { return [] } },
    displayType: { type: [String], default: 'BUTTON' },
  },
  data() {
    return {
      loading: false,
      downloadPercent : '',
    }
  },
  methods: {
    showConfirm() {
      if (this.rows.length == 0) {
        this.$message.error('请至少选择一个文件')
        return
      }
      this.handleDownload()
    },
    handleDownload() {
      let selectedIds = this.rows.map(item => item.id)
      this.loading = true
      this.downloadPercent = '0%'
      let _this = this
      axios({
        method: 'post',
        url: '/backend/analysis/downloadBioFile',
        data: selectedIds,
        responseType: 'blob',
        onDownloadProgress: function (progressEvent) {
          let loaded = progressEvent.loaded
          let total = progressEvent.total
          _this.downloadPercent = parseInt((loaded / total) * 100) + '%'
        },
      }).then((res) => {
        let allowfilesize = res.headers.allowfilesize
        if (allowfilesize) {
          this.$message.error('批量下载的文件数超过允许的上限数（' + allowfilesize + '），无法下载')
          return
        }

        let filename = decodeURIComponent(res.headers.filename)
        let filesize = parseInt(res.headers.filesize)
        console.log('document file download, get size: ' + filesize)
        if (selectedIds.length > filesize) {
          if (this.displayType == 'BUTTON') {
            this.$message.warn('部分文件不存在，可能已被后台删除，它们将被忽略')
          } else {
            this.$message.warn('文件不存在，可能已经在后台被删除')
          }
        }
        if(filesize == 0) {
          return
        }

        if (!res.data) {
          return
        }
        let url = window.URL.createObjectURL(res.data)
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.download = filename
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href)
      }).finally(() => {
        this.loading = false
        this.downloadPercent = ''
      })
    },
  }
}
</script>
